<?php

class Admin_WidgetsController extends Zend_Controller_Action
{
	// Do some checks here (including authorization)
	public function init()
	{
		parent::init();

		$sessAccount = Account_Model_Session::getAccount();
		if ($sessAccount === NULL) {
			$this->_redirect('/');
		}
		$gOpts = Kernel::getInstance()->getOptions();
		if (is_array($gOpts['site']) && is_array($gOpts['site']['administrator'])
			&& isset($gOpts['site']['administrator']['idname'])) {
			if ($sessAccount->getIdName() != $gOpts['site']['administrator']['idname']) {
				$this->_redirect('/');
			}
		}
	}


	public function indexAction()
	{
		$widgets = Kernel::getInstance()->getWidgetList();

		$viewWidgets = array();

		foreach ($widgets as $wgt) {
			$m = array();
			$m['idname'] = $wgt->getIdName();
			$m['name'] = $wgt->getName();
			$m['desc'] = $wgt->getDescription();
			$m['active'] = $wgt->getActive();
			$m['module'] = $wgt->getOwner();
			if ($wgt->getActive()) {
				$m['activeOpUrl'] = site_url_base('/admin/widget/'. $wgt->getIdName() .'/deactivate');
				$m['activeOp'] = 'Deactivate';
			} else {
				$m['activeOpUrl'] = site_url_base('/admin/widget/'. $wgt->getIdName() .'/activate');
				$m['activeOp'] = 'Activate';
			}
			$viewWidgets[] = (object)$m;
		}

		$this->view->widgetCount = count($viewWidgets);
		$this->view->widgetList = $viewWidgets;


		Kernel::getInstance()->setHeadTitle('Admin: Widgets');

		$this->view->singleWidgetPageTitle = 'Widget List';
		$this->view->singleWidgetPage = TRUE;
	}


	public function activateAction()
	{
		$idname = $this->_getParam('widget_idname');
		if (empty($idname)) {
			//TODO: show error
			$this->_redirect('/admin/widgets');
		}
		Admin_Model_Widget::activate($idname, TRUE);
		$this->_redirect('/admin/widgets');
	}

	public function deactivateAction()
	{
		$idname = $this->_getParam('widget_idname');
		if (empty($idname)) {
			//TODO: show error
			$this->_redirect('/admin/widgets');
		}
		Admin_Model_Widget::activate($idname, FALSE);
		$this->_redirect('/admin/widgets');
	}
}
